package com.zllkj.mm.module.home.fragments

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.zllkj.mm.R
import com.zllkj.mm.adapter.MyAddressListAdapter
import com.zllkj.mm.adapter.OrderConfirmListAdapter
import com.zllkj.mm.api.network.RetrofitHelper
import com.zllkj.mm.api.network.RxHelper
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber
import com.zllkj.mm.base.BaseFragment
import com.zllkj.mm.base.BaseTitleFragment
import com.zllkj.mm.model.entity.AddressBeanVo
import com.zllkj.mm.model.entity.AddressListOutSideBean
import com.zllkj.mm.module.shopping.vm.ItemMyAddressListVM
import com.zllkj.mm.util.JsonUtil
import com.zllkj.mm.util.common.AppUtils
import kotlinx.android.synthetic.main.fragment_address_list.*
import kotlinx.android.synthetic.main.fragment_address_list.view.*
import kotlinx.android.synthetic.main.fragment_mycollection.view.*
import kotlinx.android.synthetic.main.fragment_order_confirm.view.*
import kotlinx.android.synthetic.main.fragment_order_confirm.view.rv_order_confirm
import java.util.HashMap

class MyAddressListFragment : BaseTitleFragment() {

    lateinit var listAdapter : MyAddressListAdapter

    var datas = ArrayList<ItemMyAddressListVM>()

    var isModify = false

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_address_list
    }

    override fun loadData() {
        super.loadData()

        setCommonTitle("地址列表")
        setRightBtn("管理", View.OnClickListener {
            if (!isModify) {
                mRootView.btn_address_list_add.text = "刪除"
                isModify = true
            } else {
                mRootView.btn_address_list_add.text = "添加地址"
                isModify = false
            }
            datas.map {
                it.isModify = isModify
            }
            listAdapter.notifyDataSetChanged()
        })

        listAdapter = MyAddressListAdapter(R.layout.item_address_list,datas)
        mRootView.rv_address_list.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = listAdapter
        }

        mRootView.btn_address_list_add.setOnClickListener {
            if (isModify) {
                deleteAddress()
            } else {
                addFragment(AddressModifyFragment(""))
            }
        }

        loadAddressList()
    }

    fun deleteAddress(){
        var deleteAddressId = ArrayList<String>()
        datas.map {
            if (it.isCheck) deleteAddressId.add(it.id)
        }
        addSubscribe(RetrofitHelper.getInstance().addressApi.deleteAddress((HashMap<String, Any>().apply {
            this["userAddressIds"] = JsonUtil.GsonString(deleteAddressId).replace("\"", "").replace("[", "").replace("]", "")
        })).compose<Any>(RxHelper.defaultHandleResult<Any>()).subscribe(object : ProgressSubscriber<Any>(context){
            override fun onSucc(t: Any?) {
                datas.clear()
                loadAddressList()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }


    override fun notifyDataUpdate(intent: Intent?) {
        super.notifyDataUpdate(intent)

        if (intent?.action == BaseFragment.ACTION_FRAGMENT_UPDATE) {
            if (intent?.getBooleanExtra(AppUtils.KEY_OF_ADDRESS_UPDATE,false) == true){
                datas.clear()
                loadAddressList()
            }
        }
    }

    /**
     * 加载默认地址
     */
    fun loadAddressList(){
        addSubscribe(RetrofitHelper.getInstance().addressApi.getAddressList((HashMap<String, Any>().apply {
            this["pageSize"] = 20
            this["currentPage"] = 1
        })).compose<AddressListOutSideBean>(RxHelper.defaultHandleResult<AddressListOutSideBean>()).subscribe(object : ProgressSubscriber<AddressListOutSideBean>(context){
            override fun onSucc(t: AddressListOutSideBean) {
                t?.records.map {
                    var vm = ItemMyAddressListVM()
                    vm.id = it.receivingAddressId.toString()
                    vm.name = it.receiverName
                    vm.phone = it.receiverPhone
                    vm.address = it.city + it.province + it.province + it.detailAddress
                    datas.add(vm)
                }
                listAdapter.setNewData(datas)
                var emptyView = layoutInflater.inflate(R.layout.include_empty_layout,null).apply {
                    findViewById<AppCompatImageView>(R.id.iv_empty_icon).setImageResource(R.mipmap.ic_empty_address)
                    findViewById<AppCompatTextView>(R.id.tv_empty_title).text = "你还没有添加地址哦~"
                    findViewById<AppCompatTextView>(R.id.tv_empty_content).text = "去添加地址哦~~"
                }
                listAdapter.emptyView = emptyView
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))

        listAdapter.setOnItemChildClickListener { baseQuickAdapter, view, i ->
            if (view.id == R.id.iv_item_address_modify){
                addFragment(AddressModifyFragment(datas[i].id))
            }
        }

        listAdapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            AppUtils.putFragmentData("addressItem",datas[i])
            removeFragment()
        }
    }
}